#!/usr/bin/env python

'''
Convert Daintree SNA files to libpcap format and vice-versa.

Note: timestamps are not preserved in the conversion process. Sorry.
(jwright@willhackforsushi.com)
'''

import sys
import os.path
import argparse

from killerbee import *

# Command-line arguments
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-i', '--infile', action='store', required=True)
parser.add_argument('-o', '--outfile', action='store', required=True)
parser.add_argument('-n', '--noclobber', action='store_true')
parser.add_argument('-c', '--count', action='store', type=int, default=-1)
args = parser.parse_args()

if args.noclobber and os.path.exists(args.outfile):
    print >>sys.stderr, "ERROR: Output file \"%s\" already exists." % args.outfile
    sys.exit(1)

if not os.path.exists(args.infile):
    print >>sys.stderr, "ERROR: Input file \"%s\" does not exist." % args.infile
    sys.exit(1)

# Check if the input file is libpcap; if not, assume SNA.
outcap = None
try:
    pr = PcapReader(args.infile)
except Exception, e:
    if e.args == ('Unsupported pcap header format or version',):
        # Input file was not pcap, open it as SNA
        incap = DainTreeReader(args.infile)
        outcap = PcapDumper(DLT_IEEE802_15_4, args.outfile)
# Following exception
if outcap is None:
        incap = pr
        outcap = DainTreeDumper(args.outfile)

packetcount = 0
while args.count != packetcount:
    packet = incap.pnext()
    if packet[1] is None: # End of capture
        break

    # packet[1] is True if CRC is correct, check removed to have conversion regardless of CRC
    if packet is not None: # and packet[1]:
        packetcount += 1
        outcap.pcap_dump(packet[1])

incap.close()
outcap.close()
print("Converted {0} packets.".format(packetcount))

